package com.cgah

import javax.servlet.http.HttpServletResponse
import util.converters.JSON
import com.cgah.exceptions.BidNotFoundException
//import grails.converters.*;


class BidController {
    // injected
    def springSecurityService;
    def bidService;
    def listingService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]


    def index = {
        redirect(action: "list", params: params)
    }


    def list = {
        [bidInstanceList: bidService.list(params), bidInstanceTotal: bidService.countOfBids()]
    }


    def create = {
        return [bidInstance: bidService.create(params)]
    }


    def save = {
        def bidInstance = bidService.save(params, springSecurityService.currentUser.id);
        if (!bidInstance.hasErrors()) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
            redirect(action: "show", id: bidInstance.id)
        } else {
            render(view: "create", model: [bidInstance: bidInstance])
        }
    }


    def show = {
        try {
            return [bidInstance: bidService.getBidById(params.id)]
        } catch (BidNotFoundException bnfe) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }


    def edit = {
        try {
            return [bidInstance: bidService.getBidById(params.id)]
        } catch (BidNotFoundException bnfe) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }


    def update = {
        try {
            def bidInstance = bidService.updateBidWithParams(params, springSecurityService.currentUser.id);
            if (!bidInstance.hasErrors()) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
                redirect(action: "show", id: bidInstance.id)

            } else {
                render(view: "edit", model: [bidInstance: bidInstance])
            }
        } catch (BidNotFoundException bnfe) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }


    def delete = {
        try {
            bidService.deleteBidById(params.id)
            flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])}"
            redirect(action: "list")
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "show", id: params.id)
        } catch (BidNotFoundException bnfe) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }


    def asyncAddBid = {
        def bidInstance = bidService.save(params, springSecurityService.currentUser.id);
        if (bidInstance) {
            flash.message = "Bid successfull."
            JSONResponseMessage message = new JSONResponseMessage(
                    new BidJsonResponse(bidInstance.id, bidInstance.amount, bidInstance.nextMinBid, bidInstance.dateTime, bidInstance.customer?.username),
                    "Bid successfull.");
            response.setStatus(HttpServletResponse.SC_OK, "OK");
            response.contentType = "application/json"
            // ok i can't use this in unit testing, idfky
            // render message.encodeAsJSON()

            // see bug http://jira.grails.org/browse/GRAILS-6222
            // because grails fuking fails.
            // render message as JSON;

            // and the workaround YAY? NOT! FAIL!
            render new JSON(message);
        } else {
            flash.message = "Bid creation FAILED.  Verify your bid is \$0.50 more."
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST, "Bid creation FAILED.  Verify your bid is \$0.50 more.");
            //response.setContentType("application/json");
            // ok i can't use this in unit testing, idfky
            // render message.encodeAsJSON()
            // see bug http://jira.grails.org/browse/GRAILS-6222
            // because grails fuking fails.
            // render message as JSON;
            render(text: "Bid creation FAILED.  Verify your bid is \$0.50 more.")
        }
    }
}

// this is sooooooo stupid.  I must be missing something super obvious!
class JSONResponseMessage {
    def message;
    def status = HttpServletResponse.SC_OK;
    def bid;

    JSONResponseMessage(BidJsonResponse bid, String message) {
        this.message = message;
        this.bid = bid;
    }
}

